package com.smartleanx.module.hrm.api.component;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.smartleanx.framework.common.pojo.CommonResult;
import com.smartleanx.module.hrm.component.DocComponentApi;
import com.smartleanx.module.hrm.service.esign.ESignUrlConstant;
import com.smartleanx.module.hrm.service.esign.service.HrmECustomComponentsService;
import com.smartleanx.module.hrm.service.esign.temp.po.HrmECustomComponents;
import com.smartleanx.module.hrm.util.esign.ESignUtil;
import com.smartleanx.module.hrm.util.esign.EsignHttpResponse;
import com.smartleanx.module.hrm.util.esign.enums.EsignRequestType;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;

@RestController // 提供 RESTful API 接口，给 Feign 调用
@Validated
@Component
public class DocComponentImplApi implements DocComponentApi {

    @Value("${esign.url}")
    private String esignUrl;

    @Autowired
    private HrmECustomComponentsService hrmECustomComponentsService;

    @Override
    public CommonResult<Object> createComponent(JSONObject param) {

        // 请求地址
        String apiaddr = ESignUrlConstant.CUSTOM_COMPONENTS_CREATE;
        // 请求方法
        EsignRequestType requestType = EsignRequestType.POST;

        // 遍历要新增的控件，因为不能使用name作为唯一值，只能单独调用e接口
        JSONArray paramComponents = param.getJSONArray("components");
        for (int i = 0; i < paramComponents.size(); i++) {
            JSONObject comp = paramComponents.getJSONObject(i);

            JSONObject parram = new JSONObject();
            JSONArray jsonAr = new JSONArray();
            jsonAr.add(comp);
            parram.set("components", jsonAr);
            String jsonParm = parram.toString();

            EsignHttpResponse esignHttpResponse = ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);
            Gson gson = new Gson();
            JsonObject esignResponse = gson.fromJson(esignHttpResponse.getBody(), JsonObject.class);
            if (esignResponse.get("code").getAsInt() != 0) {
                // throw exception(ErrorCodeConstants.E_SIGN_API_ERROR);
            } else {
                // E签宝响应的id和name
                JsonObject esignResponseData = esignResponse.getAsJsonObject("data");
                JsonArray customComponents = esignResponseData.getAsJsonArray("customComponents");
                JsonObject customComponent = customComponents.get(0).getAsJsonObject();

                HrmECustomComponents insert = new HrmECustomComponents();
                insert.setDataStatus(1);
                insert.setComponentId(customComponent.get("customComponentId").getAsString());
                insert.setComponentKey(comp.getStr("customBizNum"));
                insert.setComponentName(customComponent.get("customComponentName").getAsString());
                insert.setComponentType(1);
                hrmECustomComponentsService.save(insert);
            }
        }
        return CommonResult.success(true);
    }

    @Override
    public CommonResult<Object> deleteComponent(List<Long> fieldIds) {
        String apiaddr = ESignUrlConstant.CUSTOM_COMPONENTS_REMOVE;
        // 请求方法
        EsignRequestType requestType = EsignRequestType.POST;
        if (fieldIds != null && !fieldIds.isEmpty()) {
            JSONArray jsonArray = new JSONArray();
            for (Long fieldId : fieldIds) {
                HrmECustomComponents one =
                    hrmECustomComponentsService.getOne(new LambdaQueryWrapper<HrmECustomComponents>() {
                        {
                            eq(HrmECustomComponents::getComponentKey, "" + fieldId);
                            last("limit 1");
                        }
                    });
                jsonArray.add(one.getComponentId());
                hrmECustomComponentsService.removeById(one.getId());
            }

            JSONObject parram = new JSONObject();
            parram.set("componentId", jsonArray);
            String jsonParm = parram.toString();
            ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);
        }
        return CommonResult.success(true);
    }

    @Override
    public CommonResult<Object> updateComponent(Map<Long, String> fieldMap) {
        String apiaddr = ESignUrlConstant.CUSTOM_COMPONENTS_RENAME;
        // 请求方法
        EsignRequestType requestType = EsignRequestType.POST;
        Set<Long> ids = fieldMap.keySet();
        for (Long id : ids) {
            String componentKey = "" + id;
            HrmECustomComponents one =
                hrmECustomComponentsService.getOne(new LambdaQueryWrapper<HrmECustomComponents>() {
                    {
                        eq(HrmECustomComponents::getComponentKey, componentKey);
                        last("limit 1");
                    }
                });
            // 名称有变化再更新e签宝
            if (one != null && !one.getComponentName().equals(fieldMap.get(id))) {
                hrmECustomComponentsService.update(null, new LambdaUpdateWrapper<HrmECustomComponents>() {
                    {
                        eq(HrmECustomComponents::getId, one.getId());
                        set(HrmECustomComponents::getComponentName, fieldMap.get(id));
                    }
                });
                JSONObject param = new JSONObject();
                param.set("componentId", one.getComponentId());
                param.set("componentName", fieldMap.get(id));
                String jsonParm = param.toString();
                ESignUtil.sendHttpResponse(jsonParm, requestType, apiaddr, esignUrl);
            }
        }
        return CommonResult.success(true);
    }
}
